class SharerController < ApplicationController

  def index
    @page_title = "Favorite to microblog_Microblog"
    if request.post?
      favorite = Favorite.new
      user_id = get_user_id
      unless user_id
        # Only works when user logged in
        # Code add here to redirect user to login
        # Salve this problem later
      else
        favorite.user_id = user_id
        favorite.title = params[:title]
        favorite.url = params[:url]
        favorite.description = text_process(params[:detail])
        favorite.favorite_at = Time.now
        # 'Cause window will close soon, Just save it.
        # do nothing else.
        favorite.save
      end
    end
  end
  
  def get_user_id
    if session[:user_name].nil?
      return false
    end
    users = User.find(:all, :conditions => ["name='#{session[:user_name]}'"])
    users[0].id
  end
  
  private
  
  # Text processing here is a little different from the message. #
  def text_process(text)
    text.strip!
    #get rid of all the special chars
    text.gsub!(/[\n\r\s\t]+/mu," ")
    # A little different from the message. #
    # use jtext to solve the dirty problem.
    # I don't know if there is a slice method for
    # unicode.
    count = 0
    new_text = ''
    text.each_char do |mb|
      new_text += mb
      count += 1
      break if count >= 140
    end
    # add @ processing and url trim here.
    return new_text
  end

end
